package com.mysiteforme.admin.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.entity.user.ChUser;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.service.user.ChUserService;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yj
 * @since 2019-04-15
 */
@Controller
@RequestMapping("/chUser")
public class ChUserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChUserController.class);

    @Autowired
    private ChUserService chUserService;

    @GetMapping("list")
    @SysLog("跳转列表")
    public String list() {
        return "/ytzluser/chUser/list";
    }


    @PostMapping("list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChUser> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                  @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                  ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<ChUser> layerData = new LayerData<>();
        EntityWrapper<ChUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.isWhere(true);
        //验证登录用户角色
        boolean a = SecurityUtils.getSubject().hasRole("系主任");
        boolean b = SecurityUtils.getSubject().hasRole("班主任");
        boolean c = SecurityUtils.getSubject().hasRole("教师");
        //拼接sql
        if (map.get("select_realInfo") != null && map.get("select_realInfo") != "") {
            String condition = (String) map.get("select_realInfo");
            entityWrapper.like("u.user_number", "%" + condition + "%")
                    .or().like("u.user_account", "%" + condition + "%")
                    .or().like("u.real_name", "%" + condition + "%");
        }
        if (map.get("classId") != null && map.get("classId") != "") {
            String classId = (String) map.get("classId");
            entityWrapper.andNew().eq("u.class_id", classId);
        }
        if (map.get("departmentId") != null && map.get("departmentId") != "") {
            String departmentId = (String) map.get("departmentId");
            entityWrapper.andNew().eq("c.department_id", departmentId);
        }

        if (map.get("schoolId") != null && map.get("schoolId") != "") {
            String schoolId = (String) map.get("schoolId");
            entityWrapper.andNew().eq("d.school_id", schoolId);
        }
        if (a) {
            String deanId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            entityWrapper.andNew().eq("d.dean_id", deanId);
        }
        if (b) {
            String headTeacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            entityWrapper.andNew().eq("c.head_teacher_id", headTeacherId);
        }
        if (c) {
            String teacherId = ((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString();
            entityWrapper.andNew().eq("c.teacher_id", teacherId);
        }
        Page<ChUser> pageData = chUserService.selectByEntityWrapper(new Page<>(page, limit), entityWrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @PostMapping("/getUserInfo")
    @ResponseBody
    @SysLog("获取单个用户数据")
    public ChUser getUserInfo(@RequestParam("userNumber") String userNumber) {
        if (userNumber != null && userNumber != "") {
            ChUser chUser = chUserService.findByUserNumber(userNumber.trim());
            if (chUser != null) {
                return chUser;
            } else {
                System.out.println("空");
                return null;
            }
        } else
            return null;
    }

    @GetMapping("active")
    @SysLog("跳转激活页面")
    public String active() {
        return "/ytzluser/chUser/active";
    }


    @PostMapping("active")
    @SysLog("保存激活数据")
    @ResponseBody
    public RestResponse active(@RequestParam("ids") String ids,
                               @RequestParam("inSchoolDate") String inSchoolDate,
                               @RequestParam("outSchoolDate") String outSchoolDate) throws ParseException {
        //验证入学时间必须小于毕业时间
        Date in = new SimpleDateFormat("yyyy-MM-dd").parse(inSchoolDate);
        Date out = new SimpleDateFormat("yyyy-MM-dd").parse(outSchoolDate);
        if (in.getTime() >= out.getTime()) {
            return RestResponse.failure("毕业时间必须大于入学时间，请重新选择");
        }
        //将所有查询信息存入map
        Map<String, Object> map = new HashMap<>();
        map.put("ids", "(" + ids + ")");
        map.put("inSchoolDate", inSchoolDate);
        map.put("outSchoolDate", outSchoolDate);
        map.put("modifyDate", new Date());
        map.put("isActivated", 1);
        chUserService.active(map);
        return RestResponse.success();
    }


    @PostMapping("wake")
    @SysLog("激活单个用户")
    @ResponseBody
    public RestResponse wake(@RequestParam("id") String id,
                             @RequestParam("wake") Boolean wake) {
        boolean res;
        if (id != null && id != "") {
            if (wake) {
                res = chUserService.wake(id, 1);
                return RestResponse.success("激活成功");
            } else if (!wake) {
                res = chUserService.wake(id, 2);
                return RestResponse.success("禁用成功");
            }
            return RestResponse.failure("系统繁忙");
        } else {
            return RestResponse.failure("请重新选择需要操作的用户");
        }

    }

    @PostMapping("check")
    @SysLog("激活单个用户")
    @ResponseBody
    public RestResponse check(@RequestParam("userNumber") String id, @RequestParam("realName") String realName) {
        ChUser chUser = chUserService.findByUserNumber(id);
        if (chUser.getRealName().equals(realName)) {
            return RestResponse.success();
        } else {
            return RestResponse.failure("验证错误");
        }
    }


    @GetMapping("editor")
    @SysLog("编辑学生信息")
    public String edit() {
        return "ytzluser/chUser/edit";
    }


    @PostMapping("editor")
    @SysLog("编辑学生信息")
    @ResponseBody
    public RestResponse editor(String id, String userNumber,
                               String userAccount, String realName,
                               String idCard, String inSchoolDate, String outSchoolDate) throws Exception {
        if ("".equals(id)) {
            return RestResponse.failure("用户id不能为空");
        }
        if ("".equals(userNumber) && "".equals(userAccount) && "".equals(idCard) && "".equals(inSchoolDate) && "".equals(outSchoolDate)) {
            return RestResponse.failure("传递的数据不能为空");
        }
        //认证接口
        ChUser chUser = chUserService.selectByStudentInfo(id);
        //拿到原身份证号
        String cardId = chUser.getIdCard();
        //拿到原学号
        String userNo = chUser.getUserNumber();
        //拿到原手机号
        String phone = chUser.getUserAccount();

        if (!userNo.equals(userNumber)) {
           Integer count = chUserService.selectUserNumberCount(userNumber);
           if (count>0){
               return RestResponse.failure("学号已存在,请重新输入");
           }
        }
        if (!phone.equals(userAccount)) {
            Integer  count =chUserService.selectUserAccountCount(userAccount);
            if (count>0){
                return RestResponse.failure("手机号已存在,请重新输入");
            }
        }
        if (!cardId.equals(idCard)) {
            Integer  count  =chUserService.selectIdCardCount(idCard);
            if (count>0) {
                return RestResponse.failure("身份证号已存在,请重新入");
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("userNumber", userNumber);
        param.put("userAccount", userAccount);
        param.put("realName", realName);
        param.put("idCard", idCard);
        param.put("inSchoolDate", sdf.parse(inSchoolDate));
        param.put("outSchoolDate", sdf.parse(outSchoolDate));
        Integer integer = chUserService.editor(param);
        if (integer > 0) {
            return RestResponse.success("编辑成功");
        }
        return RestResponse.failure("编辑失败");
    }

    @GetMapping("distributionClass")
    @SysLog("跳转分配班级页面")
    public String distribution() {
        return "/ytzluser/chUser/distributionClass";
    }

    @PostMapping("distributionClass")
    @SysLog("分配班级")
    @ResponseBody
    public RestResponse distributionClass(@RequestParam("ids") String ids,
                                          @RequestParam("classId") String classId) {
        if ("".equals(classId)) {
            return RestResponse.failure("请选择班级");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("ids", "(" + ids + ")");
        param.put("classId", classId);
        Integer integer = chUserService.distributionClass(param);
        if (integer > 0) {
            return RestResponse.success("分配班级成功");
        }
        return RestResponse.failure("分配失败");
    }


}